<template>
    <el-container class="content">
        <el-main>
            <el-container class="white-block box full" v-loading="loading">
                <el-header :height="'auto'">
                    <breadcrumb :title="'后台账户设置'" :noBack="true"></breadcrumb>
                    <div class="toolbar">
                        <div>
                            <el-input v-model="key" placeholder="请输入姓名、账号" class="input"
                                      clearable></el-input>
                            <el-cascader v-model="ward" ref="floor" clearable
                                         :separator="' '"
                                         :show-all-levels="false"
                                         @change="changeFloor"
                                         placeholder="请选择病区"
                                         :props="{label:'name',value:'treeId',children:'children'}"
                                         :options="floorInfo">
                            </el-cascader>
                            <el-button type="primary" @click="getList(1)">查询</el-button>
                        </div>
                        <div class="text-right">
                            <el-button class="primary" @click="onShowCreate()">新增</el-button>
                        </div>
                    </div>
                </el-header>
                <el-main class="mt10">
                    <table-example ref="table" :data="tableData" :tableColumn="header" :slotColumns="slotColumns"
                                   :stripe="true" :height="'100%'">
                        <template slot="inpatientAreaName" slot-scope="scope">
                            {{scope.row.inpatientAreaName || '-'}}
                        </template>
                        <template slot="operation" slot-scope="scope">
                            <div class="operation">
                                <el-link type="primary" :underline="false" @click="approval(scope.row, scope.row.state)"
                                         v-if="scope.row.state == 1">启用
                                </el-link>
                                <el-link type="primary" :underline="false" @click="approval(scope.row, scope.row.state)"
                                         v-else>禁用
                                </el-link>
                                <el-link type="primary" :underline="false" @click="onShowUpdate(scope.row)">修改
                                </el-link>
                                <el-link type="primary" :underline="false" class="error"
                                         @click="deleteById(scope.row.id)">删除
                                </el-link>
                                <el-link type="primary" :underline="false" class="success"
                                         @click="onShowPwdModify(scope.row)">修改密码
                                </el-link>
                            </div>
                        </template>
                    </table-example>
                </el-main>
                <el-footer :height="'auto'" class="mt20">
                    <page :data="page" @jumpPage="getList"></page>
                </el-footer>
            </el-container>

            <dialog-msk :show.sync="showCreate" title="添加后台账户" :width="'450px'" @save="saveManager"
                        @cancel="closeDialog"
                        v-loading="dialogLoading"
                        element-loading-background="rgba(0, 0, 0, 0.3)">
                <el-form class="form-common" :model="managerNew" :rules="rulesSave" ref="createForm"
                         size="small" label-width="90px" :label-position="'right'">
                    <el-form-item label="登录账号" prop="phone">
                        <el-input v-model="managerNew.phone" size="small" placeholder="请设置登录账号" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="managerNew.name" size="small" placeholder="请输入姓名" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" size="small" v-model="managerNew.password"
                                  auto-complete="off" placeholder="请填写密码(6-18位数字/字母组合 可包含字符)"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="passwordAgain">
                        <el-input placeholder="请确认密码" v-model="managerNew.passwordAgain" type="password"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="角色" prop="role">
                        <el-select v-model="managerNew.role" class="full">
                            <el-option
                                v-for="item in roleOptions"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="管辖病区" prop="inpatientAreaId" v-if="managerNew.role==3">
                        <el-cascader v-model="managerNew.inpatientAreaId" ref="inpatientArea" class="full"
                                     clearable
                                     :show-all-levels="false"
                                     :separator="' '"
                                     @change="changeFloor"
                                     placeholder="请选择病区"
                                     :props="{label:'name',value:'treeId',children:'children'}"
                                     :options="floorInfo">
                        </el-cascader>
                    </el-form-item>
                </el-form>
            </dialog-msk>
            <dialog-msk :show.sync="showUpdate" title="修改后台账户" :width="'450px'" @save="updateManager"
                        @cancel="closeDialog"
                        v-loading="dialogLoading"
                        element-loading-background="rgba(0, 0, 0, 0.3)">
                <el-form class="form-common" :model="managerUpdate" :rules="rulesUpdate" ref="updateForm"
                         size="small" label-width="90px" :label-position="'right'">
                    <el-form-item label="登录账号">
                        <el-input v-model="managerUpdate.phone" size="small" placeholder="请设置登录账号" :disabled="true"
                                  clearable></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="managerUpdate.name" size="small" placeholder="请输入姓名" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="角色">
                        <el-select v-model="managerUpdate.roleName" class="full" disabled>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="管辖病区" v-if="managerUpdate.roleId==3">
                        <el-select v-model="managerUpdate.inpatientAreaName" class="full" disabled>
                        </el-select>
                    </el-form-item>
                </el-form>
            </dialog-msk>
            <dialog-msk :show.sync="showPwdModify" title="修改密码" :width="'450px'" @save="modifyPassword"
                        @cancel="closeDialog"
                        v-loading="dialogLoading"
                        element-loading-background="rgba(0, 0, 0, 0.3)">
                <el-form class="form-common" :model="managerPwdModify" :rules="rulesPwdModify" ref="pwdModifyForm"
                         size="small" label-width="90px" :label-position="'right'">
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" size="small" v-model="managerPwdModify.password"
                                  auto-complete="off" placeholder="请填写密码(6-18位数字/字母组合 可包含字符)"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="passwordAgain">
                        <el-input placeholder="请确认密码" v-model="managerPwdModify.passwordAgain" type="password"
                        ></el-input>
                    </el-form-item>
                </el-form>
            </dialog-msk>
        </el-main>
    </el-container>
</template>

<script>
    import tableExample from '../components/table'
    import page from '../components/pagination'
    import dialogMsk from '../components/dialog'
    import breadcrumb from '../components/breadcrumb'

    const sha256 = require('js-sha256').sha256
    export default {
        data() {
            let _this = this, RegExp = /(?=.*([a-zA-Z].*))(?=.*[0-9].*)[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,18}$/,
                Reg = /^[^ ]+$/,
                goToTheSpace = (rule, value, callback) => {
                    if (!Reg.test(value)) {
                        callback(new Error('不能输入空格!'))
                    } else {
                        callback()
                    }
                },
                validatePassNew = (rule, value, callback) => {
                    if (value !== _this.managerNew.password) {
                        callback(new Error('两次输入密码不一致!'))
                    } else {
                        callback()
                    }
                },
                validatePassNew2 = (rule, value, callback) => {
                    if (!RegExp.test(value)) {
                        callback(new Error('密码格式错误 密码中必须包含数字与字母'))
                    } else {
                        callback()
                    }
                },
                validatePassModify = (rule, value, callback) => {
                    if (value !== _this.managerPwdModify.password) {
                        callback(new Error('两次输入密码不一致!'))
                    } else {
                        callback()
                    }
                },
                validatePassModify2 = (rule, value, callback) => {
                    if (!RegExp.test(value)) {
                        callback(new Error('密码格式错误 密码中必须包含数字与字母'))
                    } else {
                        callback()
                    }
                }
            return {
                key: '', // 姓名、账号
                ward: [], // 病区
                currentList: null,
                showCreate: false,
                showUpdate: false,
                showPwdModify: false,
                // radio: 0,
                addShowEdit: false,
                managerNew: {
                    name: '',
                    phone: '',
                    password: '',
                    newPasswordAgain: '',
                    role: '',
                    inpatientAreaId: []
                },
                managerUpdate: {
                    phone: '',
                    name: '',
                    id: null
                },
                managerPwdModify: {
                    id: null,
                    password: ''
                },
                rulesSave: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'},
                        {validator: goToTheSpace, trigger: 'blur'}
                    ],
                    phone: [
                        {required: true, message: '请输入账号', trigger: 'blur'}
                    ],
                    role: [
                        {required: true, message: '请选择角色', trigger: 'change'}
                    ],
                    inpatientAreaId: [
                        {required: true, message: '请选择管辖病区', trigger: 'change'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, message: '请填写(6-18位数字/字母组合 可包含字符)', trigger: 'blur'},
                        {validator: validatePassNew2, trigger: 'blur'}
                    ],
                    passwordAgain: [
                        {required: true, message: '请确认新密码', trigger: 'blur'},
                        {min: 6, message: '请填写(6-18位数字/字母组合 可包含字符)', trigger: 'blur'},
                        {validator: validatePassNew, trigger: 'blur'}
                    ]
                },
                rulesUpdate: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'},
                        {validator: goToTheSpace, trigger: 'blur'}
                    ]
                },
                rulesPwdModify: {
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, message: '请填写(6-18位数字/字母组合 可包含字符)', trigger: 'blur'},
                        {validator: validatePassModify2, trigger: 'blur'}
                    ],
                    passwordAgain: [
                        {required: true, message: '请确认新密码', trigger: 'blur'},
                        {min: 6, message: '请填写(6-18位数字/字母组合 可包含字符)', trigger: 'blur'},
                        {validator: validatePassModify, trigger: 'blur'}
                    ]
                },
                tableData: [],
                header: [
                    {
                        prop: 'name',
                        label: '姓名',
                        minWidth: '100',
                        align: 'center'
                    },
                    {
                        prop: 'phone',
                        label: '登录账号',
                        minWidth: '150',
                        align: 'center'
                    },
                    {
                        prop: 'roleName',
                        label: '角色',
                        minWidth: '100',
                        align: 'center'
                    },
                    {
                        prop: 'inpatientAreaName',
                        label: '管辖病区',
                        minWidth: '150',
                        align: 'center'
                    },
                    {
                        prop: 'operation',
                        label: '操作',
                        align: 'center',
                        minWidth: '100',
                        fixed: 'right'
                    }
                ],
                slotColumns: ['inpatientAreaName', 'operation'],
                page: {},
                index: 1,
                loading: false,
                floorInfo: [], // 病区tree
                roleOptions: [], // 角色list
                dialogLoading: false
            }
        },
        mounted() {
            this.getFloorInfo()
            this.getList()
        },
        methods: {
            getFloorInfo(index) {
                this.loading = true
                this.$http.get('/patient/getTree?type=3').then(result => {
                    this.loading = false
                    if (result.success) {
                        this.floorInfo = result.data
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            changeFloor(val) {
                console.log(this.$refs['floor'].getCheckedNodes(true))
            },
            // 获取列表数据
            getList(index) {
                this.loading = true
                if (index) this.index = index
                this.$http.get('/getManager/pageManager', {
                    nameAndPhone: this.key,
                    inpatientAreaId: (this.ward && this.ward.length) ? this.$refs['floor'].getCheckedNodes(true)[0].data.id : '',
                    current: this.index || 1,
                    size: 15
                }).then(result => {
                    this.loading = false
                    if (result.success) {
                        this.tableData = result.data.records
                        this.page = result.data
                        delete this.page['records']
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            // 打开新增弹窗
            onShowCreate() {
                this.$http.get('/role/getRole').then(result => {
                    if (result.success) {
                        this.roleOptions = result.data
                        this.showCreate = true
                    }
                })
            },
            // 打开修改弹唱
            onShowUpdate(row) {
                this.managerUpdate = {...this.managerUpdate, ...row}
                this.showUpdate = true
            },
            // 打开修改密码弹窗
            onShowPwdModify(row) {
                this.showPwdModify = true
                this.managerPwdModify = {
                    id: row.id,
                    password: ''
                }
            },
            closeDialog() {
                if (this.$refs.createForm) this.$refs.createForm.resetFields()
                if (this.$refs.updateForm) this.$refs.updateForm.resetFields()
                if (this.$refs.pwdModifyForm) this.$refs.pwdModifyForm.resetFields()
                this.managerNew = {
                    name: '',
                    phone: '',
                    password: '',
                    newPasswordAgain: ''
                }
                this.managerUpdate = {
                    id: null,
                    name: '',
                    phone: ''
                }
                this.managerPwdModify = {
                    id: null,
                    password: ''
                }
                this.currentAccount = null
            },
            validate(formName, callback) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (callback) callback()
                    } else {
                        return false
                    }
                })
            },
            submitAdd(callback) {
                this.dialogLoading = true
                this.$http.post('/getManager/saveOne', {
                    password: sha256(this.managerNew.password),
                    name: this.managerNew.name,
                    phone: this.managerNew.phone,
                    inpatientAreaId: (this.managerNew.role === 3 && this.managerNew.inpatientAreaId && this.managerNew.inpatientAreaId.length) ? this.$refs['inpatientArea'].getCheckedNodes(true)[0].data.id : '',
                    roleId: this.managerNew.role
                }).then(result => {
                    this.dialogLoading = false
                    if (result.success) {
                        this.$message.success({
                            message: '添加成功。',
                            showClose: true
                        })
                        this.getList()
                        this.showCreate = false
                        if (callback) callback()
                    }
                }).catch(() => {
                    this.dialogLoading = false
                })
            },
            submitUpdate(callback) {
                this.dialogLoading = true
                this.$http.post('/getManager/updbyId', {
                    name: this.managerUpdate.name,
                    id: this.managerUpdate.id
                }).then(result => {
                    this.dialogLoading = false
                    if (result.success) {
                        this.$message.success({
                            message: '修改成功。',
                            showClose: true
                        })
                        this.getList()
                        this.showUpdate = false
                        if (callback) callback()
                    }
                }).catch(() => {
                    this.dialogLoading = false
                })
            },
            submitModifyPassword(callback) {
                this.dialogLoading = true
                this.$http.post('/getManager/modifyPassword', {
                    password: sha256(this.managerPwdModify.password),
                    id: this.managerPwdModify.id
                }).then(result => {
                    this.dialogLoading = false
                    if (result.success) {
                        this.$message.success({
                            message: '密码修改成功。',
                            showClose: true
                        })
                        this.getList()
                        this.showPwdModify = false
                        if (callback) callback()
                    }
                }).catch(() => {
                    this.dialogLoading = false
                })
            },
            saveManager() {
                let _this = this
                this.validate('createForm', () => {
                    this.submitAdd(function () {
                        _this.closeDialog()
                    })
                })
            },
            updateManager() {
                let _this = this
                this.validate('updateForm', () => {
                    this.submitUpdate(function () {
                        _this.closeDialog()
                    })
                })
            },
            modifyPassword() {
                let _this = this
                this.validate('pwdModifyForm', () => {
                    this.submitModifyPassword(function () {
                        _this.closeDialog()
                    })
                })
            },
            deleteById(id) {
                let _this = this
                this.$method.messageBox('confirm', '确定要删除吗?', (action, instance) => {
                    if (action === 'confirm') {
                        _this.$http.post('/getManager/delbyId?id=' + id
                        ).then(result => {
                            _this.getList()
                        })
                    }
                }, '', false, false)
            },
            approval(row, type) {
                let message, _this = this
                if (type !== 0) {
                    message = '是否启用该用户'
                } else {
                    message = '是否禁用该用户'
                }
                this.$method.messageBox('confirm', message, (action, instance) => {
                    if (action === 'confirm') {
                        _this.$http.post('/getManager/updStaById', {
                            id: row.id,
                            state: type
                        }).then(result => {
                            _this.getList()
                        })
                    }
                }, '', false, false)
            }
        },
        components: {
            tableExample,
            dialogMsk,
            page,
            breadcrumb
        }
    }
</script>

<style scoped lang="less">
    .content {
    }
</style>
